<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--用户数据-->
      <el-col :span="20" :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch"
          label-width="68px">
          <el-form-item label="手机号" prop="userName">
            <el-input v-model="queryParams.userName" placeholder="请输入手机号" clearable
              style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd"
              v-hasPermi="['account:add']">新增</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="userList">
          <el-table-column label="登录账号" align="center" key="phone" prop="phone" />
          <el-table-column label="登录密码" align="center" :show-overflow-tooltip="true">
            <template #default="scope">
              <span>******</span>
            </template>
          </el-table-column>
          <el-table-column label="角色" align="center" key="roleName" prop="roleName"
            :show-overflow-tooltip="true" />
          <el-table-column label="人员名称" align="center" key="nickname" prop="nickname"
            :show-overflow-tooltip="true" />
          <el-table-column label="状态" align="center" key="userState">
            <template #default="scope">
              <el-switch v-model="scope.row.userState" :active-value="0" :inactive-value="1"
                @change="handleStatusChange(scope.row)"
                :disabled='scope.row.userType ==11?true:false'></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="管理仓库" align="center" :show-overflow-tooltip="true">
            <template #default="scope">
              <span v-for="item in scope.row.warehouse" :key="item.value" :label="item.name">
                {{item.name}} &nbsp;</span>
            </template>
          </el-table-column>

          <el-table-column label="创建时间" align="center" prop="creationTime" width="160">
            <template #default="scope">
              <span>{{ parseTime(scope.row.creationTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="150"
            class-name="small-padding fixed-width">
            <template #default="scope">
              <el-tooltip content="修改" placement="top">
                <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                  v-hasPermi="['account:edit']"
                  :disabled='scope.row.userType ==11?true:false'></el-button>
              </el-tooltip>
              <el-tooltip content="删除" placement="top">
                <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                  v-hasPermi="['account:delete']"
                  :disabled='scope.row.userType ==11?true:false'></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize" @pagination="getList" />
      </el-col>
    </el-row>

    <!-- 添加或修改用户配置对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body
      :close-on-click-modal='false' :max-height="tableHeight">
      <el-form :model="form" :rules="rules" ref="userRef" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="phonenumber">
              <el-input v-model="form.phonenumber" placeholder="请输入手机号码" maxlength="11"
                :disabled='title == "修改用户"?true:false' />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户密码" prop="password">
              <el-input v-model="form.password" placeholder="请输入用户密码" type="password" maxlength="20"
                show-password />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="人员名称" prop="userName">
              <el-input v-model="form.userName" placeholder="请输入用户名称" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio label="0">正常</el-radio>
                <el-radio label="1">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="仓库" prop="postIds">
              <el-select v-model="form.postIds" filterable multiple clearable placeholder="请选择仓库">
                <el-option v-for="item in postOptions" :key="item.id" :label="item.name"
                  :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="角色" prop="roleIds">
              <el-select v-model="form.roleIds" filterable clearable placeholder="请选择角色">
                <el-option v-for="item in roleOptions" :key="item.id" :label="item.roleName"
                  :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="User">
import { getToken } from "@/utils/auth";
import {
  changeUserStatus,
  listUser,
  // resetUserPwd,
  getUser,
  updateUser,
  addUser,
  delUser,
  deptTreeSelect,
  getAuthRole,
  cangkuSel,
} from "@/api/system/user";
import useUserStore from "@/store/modules/user";
const userStore = useUserStore();
const router = useRouter();
const { proxy } = getCurrentInstance();
const userList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const dateRange = ref([]);
const deptName = ref("");
const deptOptions = ref(undefined);
const initPassword = ref(undefined);
const postOptions = ref([]);
const roleOptions = ref([]);
import { onMounted, onUnmounted } from "vue";

// 动态计算表格高度
const queryRef = ref(null);
const tableHeight = ref("calc(100vh - 380px)"); // 假设顶部保留200px
watch(
  () => showSearch.value,
  (newValue) => {
    if (newValue) {
      if (queryRef.value.$el.offsetHeight == 0) {
        setTimeout(() => {
          let hight = 230 + queryRef.value.$el.offsetHeight + "px";
          tableHeight.value = `calc(100vh - ` + hight + `)`;
        }, 200);
      }
    } else {
      tableHeight.value = "calc(100vh - 230px)";
    }
  },
  { deep: true }
);
function handleResize() {
  let hight = 230 + queryRef.value.$el.offsetHeight + "px";
  tableHeight.value = `calc(100vh - ` + hight + `)`;
}
onMounted(async () => {
  await nextTick();
  let hight = 230 + queryRef.value.$el.offsetHeight + "px";
  tableHeight.value = `calc(100vh - ` + hight + `)`;
  window.addEventListener("resize", handleResize);
});
// 移除事件监听器以防止内存泄漏
onUnmounted(() => {
  window.removeEventListener("resize", handleResize);
});
/*** 用户导入参数 */
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/system/user/importData",
});

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 50,
    userName: undefined,
    shopId: userStore.userDta.shopId,
  },
  rules: {
    userName: [
      { required: true, message: "用户名称不能为空", trigger: "blur" },
      {
        min: 1,
        max: 20,
        message: "用户名称长度必须介于 1 和 20 之间",
        trigger: "blur",
      },
    ],
    nickName: [
      { required: true, message: "用户名称不能为空", trigger: "blur" },
    ],
    password: [
      { required: true, message: "用户密码不能为空", trigger: "blur" },
      {
        min: 5,
        max: 20,
        message: "用户密码长度必须介于 5 和 20 之间",
        trigger: "blur",
      },
    ],
    email: [
      {
        type: "email",
        message: "请输入正确的邮箱地址",
        trigger: ["blur", "change"],
      },
    ],
    phonenumber: [
      {
        required: true,
        pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
        message: "请输入正确的手机号码",
        trigger: "blur",
      },
    ],
    postIds: [{ required: true, message: "请选择仓库", trigger: "change" }],
    roleIds: [{ required: true, message: "请选择角色", trigger: "change" }],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询用户列表 */
function getList() {
  let userData = queryParams.value;
  let data = {
    page: userData.pageNum,
    limit: userData.pageSize,
    userPhone: userData.userName,
    shopId: userData.shopId,
  };
  loading.value = true;
  listUser(data)
    .then((res) => {
      loading.value = false;
      userList.value = res.data;
      total.value = res.count;
    })
    .catch((r) => {
      loading.value = false;
    });
}
/** 搜索按钮操作 */
function handleQuery() {
  if (
    queryParams.value.userName == undefined ||
    queryParams.value.userName == ""
  ) {
    proxy.$modal.msgError("请输入搜索条件");
    return false;
  }
  queryParams.value.pageNum = 1;
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  getList();
}
/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$modal
    .confirm('是否确认删除用户"' + row.phone + '"的数据项？')
    .then(function () {
      return delUser({ id: row.id });
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}
/** 用户状态修改  */
function handleStatusChange(row) {
  let text = row.userState === 0 ? "启用" : "停用";
  proxy.$modal
    .confirm('确认要"' + text + '""' + row.roleName + '"用户吗?')
    .then(function () {
      return changeUserStatus({ id: row.id, state: row.userState });
    })
    .then(() => {
      proxy.$modal.msgSuccess(text + "成功");
    })
    .catch(function (err) {
      row.userState = row.userState === 0 ? 1 : 0;
    });
}

/** 重置密码按钮操作 */
function handleResetPwd(row) {
  proxy
    .$prompt('请输入"' + row.userName + '"的新密码', "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      closeOnClickModal: false,
      inputPattern: /^.{5,20}$/,
      inputErrorMessage: "用户密码长度必须介于 5 和 20 之间",
    })
    .then(({ value }) => {
      resetUserPwd(row.userId, value).then((response) => {
        proxy.$modal.msgSuccess("修改成功，新密码是：" + value);
      });
    })
    .catch(() => {});
}

/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["uploadRef"].submit();
}
/** 重置操作表单 */
function reset() {
  form.value = {
    userId: undefined,
    deptId: undefined,
    userName: undefined,
    nickName: undefined,
    password: undefined,
    phonenumber: undefined,
    email: undefined,
    sex: undefined,
    status: "0",
    remark: undefined,
    postIds: [],
    roleIds: undefined,
  };
  proxy.resetForm("userRef");
}
/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}
/** 新增按钮操作 */
async function handleAdd() {
  await cangkuSelPost();
  await getAuthPost();
  reset();
  open.value = true;
  title.value = "添加用户";
  form.value.password = initPassword.value;
}
/** 修改按钮操作 */
async function handleUpdate(row) {
  await cangkuSelPost();
  await getAuthPost();
  reset();
  getUser({ id: row.id }).then((res) => {
    console.log(res, "这是修改用户");
    form.value.phonenumber = res.data.phone;
    form.value.userName = res.data.nickname;
    form.value.postIds = res.data.ids;
    form.value.roleIds = res.data.roleIds[0];
    form.value.status = JSON.stringify(res.data.userState);
    form.value.password = res.data.pwd;
    form.value.id = res.data.id;
    open.value = true;
    title.value = "修改用户";
  });
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs["userRef"].validate((valid) => {
    if (valid) {
      let userData = queryParams.value;
      let dataUser = {
        phone: form.value.phonenumber,
        pwd: form.value.password,
        userName: form.value.userName,
        userState: form.value.status,
        ids: form.value.postIds,
        roleIds: [form.value.roleIds],
        shopId: userData.shopId,
        postId: "",
        id: form.value.id,
      };
      if (form.value.id != undefined) {
        updateUser(dataUser).then((res) => {
          if (res.status == 200) {
            proxy.$modal.msgSuccess("修改成功");
            open.value = false;
            getList();
          } else {
            proxy.$modal.msgError(res.msg);
          }
        });
      } else {
        let dataUser = {
          phone: form.value.phonenumber,
          pwd: form.value.password,
          userName: form.value.userName,
          userState: form.value.status,
          ids: form.value.postIds,
          roleIds: [form.value.roleIds],
          shopId: userData.shopId,
          postId: "",
        };
        console.log(dataUser);
        addUser(dataUser).then((res) => {
          if (res.status == 200) {
            proxy.$modal.msgSuccess("新增成功");
            open.value = false;
            getList();
          } else {
            proxy.$modal.msgError(res.msg);
          }
        });
      }
    }
  });
}
// 角色下拉
const getAuthPost = async () => {
  let userData = queryParams.value;
  await getAuthRole({ shopId: userData.shopId }).then((res) => {
    roleOptions.value = res.data;
  });
};
// 仓库下拉
const cangkuSelPost = async () => {
  let userData = queryParams.value;
  await cangkuSel({ shopId: userData.shopId }).then((res) => {
    console.log(res, ";;;;;");
    postOptions.value = res.data;
  });
};

onMounted(() => {
  getList();
});
</script>
